#include <iostream>
#include <functional>
#include <string>
#include "../muduo/include/muduo/net/TcpClient.h"
#include "../muduo/include/muduo/net/EventLoopThread.h"
#include "../muduo/include/muduo/base/CountDownLatch.h"
using namespace std;
class DictClient
{
public:
    DictClient(const string &ip, const int port)
        : _latch(1), _client(_loopthread.startLoop(), muduo::net::InetAddress(ip, port), "DictClient")
    {
        _client.setConnectionCallback(bind(&DictClient::onConnection, this, placeholders::_1));
        _client.setMessageCallback(bind(&DictClient::onMessage, this, placeholders::_1, placeholders::_2, placeholders::_3));
    }
    void connect()
    {
        _client.connect();
        _latch.wait();
    }
    bool send(const string &msg)
    {
        if (_conn->connected() == true)
        {
            _conn->send(msg);
            return true;
        }
        return false;
    }

private:
    void onConnection(const muduo::net::TcpConnectionPtr &conn)
    {
        if (conn->connected() == true)
        {
            _latch.countDown();
            _conn = conn;
            cout << "连接已建立: " << conn.get() << endl;
        }
        else
        {
            _conn.reset();
            cout << "连接已关闭" << endl;
        }
    }
    void onMessage(const muduo::net::TcpConnectionPtr &connn, muduo::net::Buffer *buffer, muduo::Timestamp time)
    {
        string msg = buffer->retrieveAllAsString();
        cout << "翻译结果： " << msg << endl;
    }

private:
    muduo::CountDownLatch _latch;
    muduo::net::EventLoopThread _loopthread;
    muduo::net::TcpClient _client;
    muduo::net::TcpConnectionPtr _conn;
};
int main()
{
    DictClient client("127.0.0.1", 8088);
    client.connect();
    while (1)
    {
        string str;
        cin >> str;
        client.send(str);
    }
    return 0;
}